package com.cskaoyan.service;

import com.cskaoyan.bean.Region;
import com.cskaoyan.bean.RegionExample;
import com.cskaoyan.mapper.RegionMapper;
import com.cskaoyan.vo.CityVo;
import com.cskaoyan.vo.CountyVo;
import com.cskaoyan.vo.ProvinceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author chen11
 */
@Service
public class RegionServiceImpl implements RegionService {

    @Autowired
    RegionMapper regionMapper;


    @Override
    public List<ProvinceVo> regionQuerry() {
        List<ProvinceVo> provinceVos = new ArrayList<>();

        RegionExample regionExample = new RegionExample();
        regionExample.createCriteria().andTypeEqualTo((byte) 1);

        List<Region> regions = regionMapper.selectByExample(regionExample);

        //把查询出的省份封装
        for(Region region:regions){
            ProvinceVo provinceVo = new ProvinceVo();
            provinceVo.setId(region.getId());
            provinceVo.setName(region.getName());
            provinceVo.setType(region.getType());
            provinceVo.setCode(region.getCode());
            provinceVos.add(provinceVo);

        }

        //查询城市
        for(ProvinceVo provinceVo:provinceVos){
            RegionExample regionExample2 = new RegionExample();
            int code = provinceVo.getCode();
            //查询条件
            regionExample2.createCriteria().andTypeEqualTo((byte) 2).andCodeBetween(code*100,code*100+100);

            List<Region> regions2 = regionMapper.selectByExample(regionExample2);
            List<CityVo> cityVos = new ArrayList<>();
            for(Region region:regions2){
                CityVo cityVo = new CityVo();
                cityVo.setId(region.getId());
                cityVo.setName(region.getName());
                cityVo.setType(region.getType());
                cityVo.setCode(region.getCode());
                cityVos.add(cityVo);

            }
            //封装
            provinceVo.setChildren(cityVos);



            for(CityVo cityVo:cityVos){
                RegionExample regionExample3 = new RegionExample();
                int code2 = cityVo.getCode();

                regionExample3.createCriteria().andTypeEqualTo((byte) 3).andCodeBetween(code2*100,code2*100+100);
                List<Region> regions3 = regionMapper.selectByExample(regionExample3);
                List<CountyVo> countyVos = new ArrayList<>();
                for(Region region:regions3){
                    CountyVo countyVo = new CountyVo();
                    countyVo.setId(region.getId());
                    countyVo.setName(region.getName());
                    countyVo.setType(region.getType());
                    countyVo.setCode(region.getCode());
                    countyVos.add(countyVo);

                }
                //封装
                cityVo.setChildren(countyVos);
            }

        }
        return provinceVos;
    }

}
